/*
* eHouse.c
*
* Created: 22/11/2012 20:03:07
*  Author: WIN
*/

#define F_CPU 3686400UL
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#include "Headers/led.h"
#include "Headers/switch.h"
#include "Headers/sound.h"

unsigned char ENABLE = 0;
unsigned char ALARM = 0;
unsigned char OVERFLOW_TIMES = 0;

void SPI_SlaveInit(void)
{
	/* Set MISO output, all others input */
	DDRB = (1<<DDB6);
	/* Enable SPI */
	SPCR = (1<<SPE)|(1<<SPIE);
}

int main(void)
{	
	initLEDport();
	initSoundPort();
	initSwitchPort();
	
	//DDRB = 0b00100001;
	//DDRC = 0b00000000;
	
	//EXTERNAL INTERRUPT0
	MCUCR |= 0b00000010;
	GICR |= 0b01000000;	
	
	SPI_SlaveInit();
	
	//SPI 
	//SPCR = 0b11000100;
	
	//TWI
	TWAR = 80;
	TWCR |= 0b00000011; 
	while(1)
	{	
		if(ENABLE)
		{
			sei();
			writeAllLEDs(0b10000000);
			while(ENABLE)
			{
				_delay_ms(1000);
			}
			
			cli();
		}
		else
		{
			cli();
			while(!ENABLE)
			{
				if(switchOn(7))
				{
					writeAllLEDs(0b00000001);
					ENABLE =1;
					_delay_ms(6000);
				}
			}
		}
	}
}			
	





ISR(SPI_STC_vect)
{
	unsigned char request = SPDR;
	//writeAllLEDs(0);
	
	if(request==0xFF)
	{		
			writeAllLEDs(request);
			ALARM = 0xFF;
			OVERFLOW_TIMES = 0;

			
			TCNT0 = 0;
			TIMSK = (1<<TOIE0);
			TCCR0 = 0x05;
			//sei();
	}
	else if(request==0x01)
	{	
		ENABLE = 0;	
		writeAllLEDs(ENABLE);
		ALARM = 0x00;
		TIMSK &= 0b11111110;
		OVERFLOW_TIMES=0;
		//if is sounding switch off
		alarmOff();
		cli();		
	}	
}


ISR(TIMER0_OVF_vect)
{
	//3686000 / 64 / 256 = 225
	//3686000 / 1024 /256 = 14 --- 1s
	//10s >> 140
	OVERFLOW_TIMES++;
	if(OVERFLOW_TIMES==140)
	{
		turnOnLED(6);
		
		if(ALARM==0xFF)
		{
			TIMSK &= 0b11111110;
			sei();
			GICR = 0b00000000;
			OVERFLOW_TIMES=0;
			writeAllLEDs(0);
			turnOnLED(2);
			alarmOn();			
		}
	
		
	}
	
	
}	
